package de.zainodis.kitchengnome.domainmodel;

import java.util.ArrayList;
import java.util.List;

import com.j256.ormlite.field.DataType;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;

import de.zainodis.kitchengnome.domainmodel.persistence.IItemListDao;
import de.zainodis.kitchengnome.domainmodel.persistence.IItemListDao.ItemListDao;

@DatabaseTable(tableName = ItemList.TYPE_NAME, daoClass = ItemListDao.class)
public class ItemList {

	public static final String TYPE_NAME = "ItemList";
	public static final String ID_FIELD = "id";
	public static final String NAME_FIELD = "name";
	public static final String TYPE_FIELD = "type";
	public static final String LAST_SAVED_FIELD = "lastSaved";

	@DatabaseField(generatedId = true, columnName = ID_FIELD)
	private long id;

	@DatabaseField(columnName = NAME_FIELD)
	private String name;

	@DatabaseField(columnName = TYPE_FIELD, dataType = DataType.ENUM_STRING)
	private ListType type = ListType.UNKNOWN;

	/**
	 * Used to determine the list that has been last edited, has the format
	 * {@link IItemListDao#DATE_TIME_FORMAT}.
	 */
	@DatabaseField(columnName = LAST_SAVED_FIELD)
	private String lastSaved;

	// Persisted manually
	private List<ListItem> items = new ArrayList<ListItem>();

	protected ItemList() {
		// For ormlites
	}

	public ItemList(String name, ListType type) {
		this.name = name;
		this.type = type;
	}

	public ItemList(ListType type) {
		this.type = type;
	}

	public long getId() {
		return id;
	}

	public String getName() {
		return name;
	}

	public List<ListItem> getItems() {
		return items;
	}

	public void setItems(List<ListItem> items) {
		this.items = items;
	}

	/**
	 * @param position
	 *           position of the list item to retrieve.
	 * @return the item at the specified position, or null if the position is
	 *         invalid or there are no {@link ListItem}s.
	 */
	public ListItem get(int position) {
		if (items != null) {
			return items.get(position);
		}
		return null;
	}

	/**
	 * Deletes all list items, where {@link ListItem#isDone()} is true.
	 */
	public void clearDone() {
		if (items != null) {
			for (int i = items.size() - 1; i > 0; i--) {
				if (items.get(i).isDone()) {
					items.remove(i);
				}
			}
		}
	}

	/**
	 * Clears the content of the {@link ItemList} by removing all
	 * {@link ListItem}s.
	 */
	public void clear() {
		if (items != null) {
			items.clear();
		}
	}

	public String getLastSaved() {
		return lastSaved;
	}

	public void setLastSaved(String lastSaved) {
		this.lastSaved = lastSaved;
	}

	public ListType getType() {
		return type;
	}
}
